<?php


namespace app\admin\controller;


use app\BaseController;
use think\facade\Db;
use think\facade\View;


class Base extends BaseController
{
    // 初始化
    protected function initialize()
    {
        // 登陆状态校验
        if (empty(session('uid')) || empty(session('name'))) {
            $this->error('非法访问,请先登录系统！', 'Login/index');
        }
        // 渲染左侧菜单
        $menu = self::getMenu();
        View::assign('menu', $menu);
    }

    // 左侧菜单初始化
    protected static function getMenu()
    {
        if (session('name') === 'admin') {
            $data = Db::name('auth_rule')->where('status', 1)->field('id,name,title,title,pid,icon')->order('sort asc')->select();
        } else {
            $user_group_id = session('admin')['group_id'];
            $user_rule_ids = Db::name('auth_group')->where('id', $user_group_id)->value('rules');
            $data = Db::name('auth_rule')->where('status', 1)->whereIn('id', $user_rule_ids)->field('id,name,title,title,pid,icon')->order('sort asc')->select();
        }
        $menu = getTree($data, 0);
        if (!empty($menu)) {
            foreach ($menu as $k => $v) {
                if (!array_key_exists('children', $v)) {
                    unset($menu[$k]);
                }
            }
        }
        return $menu;
    }
}